package cn.wolfcode.listener;

import cn.wolfcode.wolf2w.cache.service.IStrategyStatisVORedisService;
import cn.wolfcode.wolf2w.cache.service.util.RedisKeys;
import cn.wolfcode.wolf2w.cache.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.service.IStrategyService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/*
 *
 * redis数据初始化监听器
 * */
@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private IStrategyStatisVORedisService strategyStatisVORedisService;


    //当容器调用refresh()方法时马上执行下面逻辑

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //攻略表内的数据需要塞进vo
        List<Strategy> list = strategyService.list();
        //查询monggodb
        //将攻略对象转化成vo对象
        for (Strategy strategy : list) {
            //判断vo对象是否已经存在redis中
            if (strategyStatisVORedisService.isStrategyVoExists(strategy.getId())){
                continue;//如果存在，跳过当前循环
            }
            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy, vo);
            vo.setStrategyId(strategy.getId());
            String key = RedisKeys.STRATEGY_STATIS_VO.join(strategy.getId());
            template.opsForValue().set(key, JSON.toJSONString(vo));
        }
    }
}
